package cn.tedu.search.config;

import lombok.Data;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * 是一个配置类，读取属性，初始化封装一个transportclient对象
 * 在application.yml中准备属性值
 */
@Configuration
@ConfigurationProperties("es")
@Data
public class ESConfig {
    List<String> nodes;

    @Bean
    public TransportClient initTransportClient(){
        TransportClient client = null;
        try {
            // 初始化TransportClient对象
            client = new PreBuiltTransportClient(Settings.EMPTY);
            for (String node : nodes) {
                // node解析ip地址和端口
                String[] strs = node.split(":");
                String host = strs[0];
                int port = Integer.parseInt(strs[1]);
                // inetSocketTransportAddress封装使用ip和端口
                InetSocketTransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(host), port);
                client.addTransportAddress(address);
            }
        } catch (UnknownHostException unknownHostException) {
            unknownHostException.printStackTrace();
        } finally {
            return client;
        }
    }
}
